const state = {
	socketTask: null,
	timer: 1000, // 1s
	timeoutObj: null,
	messageList: [{
		messageId: '0',
		content: '',
		fromId: '',
		toId: ''
	}],
	historyList: {
		applyFriends: {},
		friends: {},
		groups: {},
		userId: "",
		verifyFriends: {}
	}

}

const mutations = {
	WEBSOCKET_INIT(state, url) {
		state.socketTask = uni.connectSocket({
			url, // url是websocket连接ip
			success() {
				console.log('websocket连接成功')
			},
			fail() {
				console.log('websocket连接失败')
			}
		})
		state.socketTask.onOpen((res) => {
			console.log('WebSocket连接正常打开中...！')
			// 注：只有连接正常打开中 ，才能正常收到消息
			state.socketTask.onMessage(res => {
				console.log(res, "websocket监听内容");
				let jsonData = JSON.parse(res.data)
				console.log(jsonData, "jsonData转换后内容");
				if (jsonData.command === 11) {
					state.messageList.push(jsonData.data)
				}
				if (jsonData.command === 20) {
					state.messageList = jsonData.data
				}

				// console.log('收到服务器内容：' + res.data)
				/* 错误 错误令牌不能为空 */
				if (res.data.code === 10008) {
					uni.showToast({
						title: res.data.msg
					})
					// uni.navigateTo({
					// 	url: '/pages/index/index'
					// })
				}

			});
		})
	},
	changeHistory(state, data) {

	},
	WEBSOCKET_SEND(state, data) {
		state.socketTask.send({
			data,
			async success(res) {
				console.log('获取信息发送的消息', data);
				console.log('消息发送成功')
				console.log(res, "sucess res");
			},
		})
	},
	HEART_WEBSOCKET(state, data) {
		// 心跳，由客户端发起
		const vm = state.socketTask
		let times = 0
		// 每 10 秒钟由客户端发送一次心跳
		this.interval = setInterval(function() {
			if (vm.socket.readyState == 1) {
				vm.send('ping')
			} else if (vm.socket.readyState == 3) {
				times += 1
				// 超时重连，最多尝试 10 次
				if (times >= 10) {
					wx.showToast({
						title: 'WebSocket 连接已断开~',
						icon: 'none',
						duration: 3000
					})
					clearInterval(vm.interval)
				}
				vm.reconnect()
			}
		}, 10000)
	},
	CLOSE_SOCKET(state) {
		if (!state.socketTask) return
		state.socketTask.close({
			success(res) {
				console.log('关闭成功', res)
			},
			fail(err) {
				console.log('关闭失败', err)
			}
		})
	}
}

const actions = {
	WEBSOCKET_INIT({
		commit
	}, url) {
		commit('WEBSOCKET_INIT', url)
	},
	WEBSOCKET_SEND({
		commit
	}, data) {
		commit('WEBSOCKET_SEND', data)
	},
	CLOSE_SOCKET({
		commit
	}) {
		commit('CLOSE_SOCKET')
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
